#include "playpcmthread.h"
#include <SDL2/SDL.h>
#include <QFile>

#define SAMPLE_RATE 44100

#define SMAPLES 1024

#define FORMAT AUDIO_S16LSB

#define SIZE 16

#define CHANNELS 2

#define BYTES_PER_SAMPLE ((SIZE * CHANNELS) / 8)

#define BUFFER_SIZE (SMAPLES * BYTES_PER_SAMPLE)

PlayPCMThread::PlayPCMThread(QObject *parent) : QThread(parent)
{
    init();
}

PlayPCMThread::~PlayPCMThread()
{

    disconnect();
    requestInterruption();

    quit();
    wait();
    qDebug() << "PlayPCMThread destroy";
}

void PlayPCMThread::init()
{
    count = 10;
    connect(this,&QThread::finished,this,&QThread::deleteLater);
}

char *buf;
int buf_size;

void pcmAudioCallback(void *userdata,
                      Uint8 * stream,
                      int len) {

    memset(stream,0,len);

    if(buf_size <= 0) {

        return;
    }

    len = (buf_size > len) ? len:buf_size;


    SDL_MixAudio(stream,(Uint8 *)buf,len,SDL_MIX_MAXVOLUME);

    buf += len;
    buf_size -= len;
}

void PlayPCMThread::run()
{

    // 初始化
    if (SDL_Init(SDL_INIT_AUDIO)) {

        qDebug() << "init audio fail";
    }

    // open
    SDL_AudioSpec spec;

    spec.freq = SAMPLE_RATE;
//    spec.format =
    spec.format = FORMAT;
    spec.channels = CHANNELS;

    // 采样数
    spec.samples = SMAPLES;

    spec.callback = pcmAudioCallback;

    if(SDL_OpenAudio(&spec, nullptr)){

        qDebug() << "audio open fail";
        SDL_Quit();
        return;
    }

    const char* audio_path = "/Users/tgy/Documents/ffmpeg/audio/in.pcm";
    QFile file(audio_path);

    if (!file.open(QFile::ReadOnly)) {

        qDebug() << "open file fail";
        SDL_CloseAudio();
        SDL_Quit();
        return;
    }

    SDL_PauseAudio(0);

    char buffer[BUFFER_SIZE];

    while (!isInterruptionRequested()) {

        if(buf_size > 0) {

            continue;
        }

        buf_size = file.read(buffer,BUFFER_SIZE);

        if(buf_size <= 0) {

            // 读取文件完成
            break;
        }

        buf = buffer;
    }

    // 关闭文件
    file.close();
    // 关闭audio
    SDL_CloseAudio();
    // 结束
    SDL_Quit();
}


